package com.idp.web.controller;

import com.idp.common.base.BaseController;
import com.idp.common.base.BaseResult;
import com.idp.common.constants.CommonConstants;
import com.idp.common.constants.Constants;
import com.idp.common.model.UploadModel;
import com.idp.common.persistence.Page;
import com.idp.common.util.UploadUtils;
import com.idp.common.util.ValidateUtils;
import com.idp.web.dto.DoctorAssignListDTO;
import com.idp.web.dto.DoctorListDTO;
import com.idp.web.entity.Department;
import com.idp.web.entity.Doctors;
import com.idp.web.entity.Orders;
import com.idp.web.service.IDepartmentService;
import com.idp.web.service.IDoctorsService;
import com.idp.web.service.IOrdersService;
import com.idp.web.vo.DoctorSearchVo;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 医生controller
 *
 * @author xubinren
 * @version 1.0
 * @date 2018/2/27
 */
@Controller
@RequestMapping("/doctors")
public class DoctorsController extends BaseController {

    private Logger logger = Logger.getLogger(DoctorsController.class);

    @Resource
    private IDoctorsService doctorsService;

    @Resource
    private IOrdersService ordersService;

    @Resource
    private IDepartmentService departmentService;

    /**
     * 初始化查询页面-管理后台
     *
     * @return String
     */
    @RequestMapping("/init")
    public String init() {
        return "backstage/doctors/doctorsSearch";
    }

    /**
     * 初始化查询页面--国内医院
     *
     * @return
     */
    @RequestMapping("/hospitalDoctorInit")
    public String hospitalNurseInit() {
        return "hospital/doctors/doctorsSearch";
    }

    /**
     * 根据条件分页查询医生列表
     *
     * @param doctorSearch 查询信息
     * @param page         分页信息
     * @param request      HttpServletRequest
     * @return String
     */
    @RequestMapping("/list")
    public String list(DoctorSearchVo doctorSearch, Page<DoctorListDTO> page, HttpServletRequest request) {
        try {
            if (getCurrentUser().getUserType() == CommonConstants.USER_TYPE_HOSPITAL){
                doctorSearch.setHospitalId(getUserId());
                doctorSearch.setUserType(CommonConstants.USER_TYPE_HOSPITAL);
            }
            request.setAttribute("page", doctorsService.findByPage(doctorSearch, page));
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        if (CommonConstants.HOSPITAL_PAGETYPE.equals(doctorSearch.getPageType())){
            return "hospital/doctors/doctorsList";
        }
        return "backstage/doctors/doctorsList";
    }

    /**
     * 分配医生--医生列表
     *
     * @param doctorSearch 查询信息
     * @param page         分页信息
     * @param request      HttpServletRequest
     * @return String
     */
    @RequestMapping("/assignList")
    public String assignList(DoctorSearchVo doctorSearch, Page<DoctorAssignListDTO> page, HttpServletRequest request) {
        //订单信息、科室信息获取
        Orders orders = ordersService.getById(doctorSearch.getOrderId());
        Department department = departmentService.getById(orders.getDepartmentId());
        if (null == orders || null == department || CommonConstants.DEPARTMENT_ROOT_ID.equals(department.getParentId())){
            return null;
        }
        doctorSearch.setDepartmentId(orders.getDepartmentId());
        doctorSearch.setDepartmentParentId(department.getParentId());

        Page<DoctorAssignListDTO> page1 = doctorsService.assignListPage(doctorSearch, page);
        request.setAttribute("assignListPage", page1);
        return "common/doctorsAssignList";
    }

    /**
     * 新增修改页面初始化
     *
     * @param doctorSearch      医生信息
     * @param request HttpServletRequest
     * @return String
     */
    @RequestMapping("/doctors")
    public String doctors(DoctorSearchVo doctorSearch, HttpServletRequest request) {
        try {
            if (null != doctorSearch && ValidateUtils.isNotEmpty(doctorSearch.getId())) {
                Doctors doctors = doctorsService.getById(doctorSearch.getId());
                request.setAttribute("doctors", doctors);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        if (CommonConstants.HOSPITAL_PAGETYPE.equals(doctorSearch.getPageType())){
            return "hospital/doctors/doctors";
        }
        return "backstage/doctors/doctors";
    }

    /**
     * 保存或修改医生信息
     * @return String
     */
    @RequestMapping("/saveOrUpdate")
    @ResponseBody
    public String saveOrUpdate(HttpServletRequest request) {

        JSONObject json = new JSONObject();
        try {
            Doctors doctors = new Doctors();
            UploadModel model = new UploadModel(UploadUtils.getServerUploadBasePath(UploadUtils.PATH_IMAGES),
                    UploadModel.IMAGES, doctors);
            UploadUtils.uploadFileSealedObject(request, model);

            //数据收集
            DoctorSearchVo doctorSearchVo = new DoctorSearchVo();
            doctorSearchVo.setUserId(getUserId());
            if (getCurrentUser().getUserType() == CommonConstants.USER_TYPE_HOSPITAL){
                doctorSearchVo.setHospitalId(getUserId());
                doctorSearchVo.setUserType(CommonConstants.USER_TYPE_HOSPITAL);
            }

            if (ValidateUtils.isNotEmpty(doctors.getId())) {
                // 修改

                //头像
                String strMiddle = request.getParameter(CommonConstants.AVATAR_URL);
                if (StringUtils.isEmpty(doctors.getAvatarUrl()) && StringUtils.isNotEmpty(strMiddle)){
                    Doctors doctors1 = doctorsService.getById(doctors.getId());
                    doctors.setAvatarUrl(doctors1.getAvatarUrl());
                }

                doctorsService.update(doctors, doctorSearchVo);
            }else {
                // 新增

                doctorsService.add(doctors, doctorSearchVo);
            }
            json.put("result", "save_success");
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            json.put("result", "save_fail");
        }
        return json.toString();
    }

    /**
     * 查看页面初始化
     *
     * @param doctorSearchVo      医生信息
     * @param request HttpServletRequest
     * @return String
     */
    @RequestMapping("/show")
    public String show(DoctorSearchVo doctorSearchVo,HttpServletRequest request) {

        try {
            if (null != doctorSearchVo && ValidateUtils.isNotEmpty(doctorSearchVo.getId())) {
                Doctors doctors = doctorsService.getById(doctorSearchVo.getId());
                request.setAttribute("doctors", doctors);
            }else {
                logger.info("参数错误");
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        if (CommonConstants.HOSPITAL_PAGETYPE.equals(doctorSearchVo.getPageType())){
            return "hospital/doctors/doctorsShow";
        }
        return "backstage/doctors/doctorsShow";
    }

    /**
     * 删除
     *
     * @return String
     */
    @RequestMapping("/delete")
    @ResponseBody
    public String delete(DoctorSearchVo doctorSearchVo) {
        JSONObject json = new JSONObject();
        try {
            doctorsService.delete(doctorSearchVo);
            json.put("result", "delete_success");
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            json.put("result", "delete_fail");
        }
        return json.toString();
    }

    /**
     * 根据医生id修改医生的账户状态
     *
     * @param id 医生id
     * @return String
     */
    @RequestMapping("/changeStatus")
    @ResponseBody
    public String changeStatus(String id) {
        JSONObject json = new JSONObject();
        if (StringUtils.isEmpty(id)){
            json.put("result", Constants.RESPONSE_MESSAGE_400);
        }else {
            BaseResult baseResult = doctorsService.changeStatus(id,getUserId());
            json.put("result", baseResult.getMessage());;
        }
        return json.toString();
    }
}
